package com.hy.demo.util;

import android.content.Context;
import android.speech.tts.TextToSpeech;

import com.hy.demo.R;
import com.hy.frame.util.LogUtil;

public class TTS {
    private static TTS _instance;
    private TextToSpeech ts;
    private Context context;
    private TextToSpeech.OnInitListener listener;
    private boolean init;
    private Runnable runnable;

    public TTS(Context context) {
        this.context = context;
    }

    public void speak(String msg) {
        if (listener == null) {
            listener = new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {
                    LogUtil.d("TTS", status);
                    init = status == TextToSpeech.SUCCESS;
                    if (init) {
                        ts.setPitch(1.0f);
                        ts.setSpeechRate(1.0f);
                        if ( runnable != null) {
                            runnable.run();
                        }
                    }
                }
            };
        }
        runnable = new Runnable() {
            @Override
            public void run() {
                runnable = null;
                if (!ts.isSpeaking()) {
                    ts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
                } else {
                    ts.speak(msg, TextToSpeech.QUEUE_ADD, null);
                }
            }
        };
        if (ts == null || !init) {
            ts = new TextToSpeech(context, listener);
        } else {
            runnable.run();
        }

    }

    public static synchronized TTS getInstance(Context context) {
        if (_instance == null) {
            _instance = new TTS(context.getApplicationContext());
        }
        return _instance;
    }
}
